import blank from '@/assets/blank.jpg'
import store from '@/store'

export default {
  getImageSrc(src) {
    if (!src) { return blank }
    return store.state.app.server_api + '/admin/common/preview/' + src
  },

  getVideoSrc(src) {
    if (!src) { return '' }
    if (src.indexOf('/') > -1) {
      return store.state.app.server_api + src
    } else {
      return store.state.app.server_api + '/admin/common/preview/' + src
    }
  },

  // Parse the time to string
  parseTime(time, cFormat) {
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      }
      if ((typeof time === 'number') && (time.toString().length === 10)) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
      const value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
      return value.toString().padStart(2, '0')
    })
    return time_str
  },

  formatTime(time, option) {
    if (('' + time).length === 10) {
      time = parseInt(time) * 1000
    } else {
      time = new Date(time.replace(/-/g, '/'))
    }

    const d = new Date(time)
    const now = Date.now()
    const diff = (now - d) / 1000

    if (diff < 30) {
      return '刚刚'
    } else if (diff < 3600) {
      // less 1 hour
      return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
      return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
      return '1天前'
    }
    if (option) {
      return this.parseTime(time, option)
    } else {
      return (
        d.getMonth() +
        1 +
        '月' +
        d.getDate() +
        '日' +
        d.getHours() +
        '时' +
        d.getMinutes() +
        '分'
      )
    }
  },

  // 计算指定时间与当前的时间差
  diffDateBefore(data) {
    // 获取比对时间
    const dateBegin = new Date(data.replace(/-/g, '/'))
    // 获取当前时间
    const dateEnd = new Date()
    const diffTime = dateEnd.getTime() - dateBegin.getTime()
    // 计算相差年数
    const yearDiff = Math.floor(diffTime / (365 * 24 * 3600 * 1000))
    if (yearDiff > 0) {
      return yearDiff + '年前'
    }
    // 计算剩余的毫秒数
    let mseceonds = diffTime % (365 * 24 * 3600 * 1000)
    const monthDiff = Math.floor(mseceonds / (30 * 24 * 3600 * 1000))
    if (monthDiff > 0) {
      return monthDiff + '月前'
    }
    mseceonds = mseceonds % (30 * 24 * 3600 * 1000)
    // 计算相差天数
    const dayDiff = Math.floor(mseceonds / (24 * 3600 * 1000))
    if (dayDiff > 0) {
      return dayDiff + '天前'
    }
    // 计算剩余的毫秒数
    mseceonds = mseceonds % (24 * 3600 * 1000)
    // 计算相差小时数
    const hours = Math.floor(mseceonds / (3600 * 1000))
    if (hours > 0) {
      return hours + '小时前'
    }
    // 计算小时数后剩余的毫秒数
    mseceonds = mseceonds % (3600 * 1000)
    // 计算相差分钟数
    const minutes = Math.floor(mseceonds / (60 * 1000))
    if (minutes > 0) {
      return minutes + '分钟前'
    }
    return '刚刚'
  },

  param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
      return {}
    }
    return JSON.parse(
      '{"' +
        decodeURIComponent(search)
          .replace(/"/g, '\\"')
          .replace(/&/g, '","')
          .replace(/=/g, '":"')
          .replace(/\+/g, ' ') +
        '"}'
    )
  },

  html2Text(val) {
    const div = document.createElement('div')
    div.innerHTML = val
    return div.textContent || div.innerText
  },

  /**
   * Merges two objects, giving the last one precedence
   * @param {Object} target
   * @param {(Object|Array)} source
   * @returns {Object}
   */
  objectMerge(target, source) {
    if (typeof target !== 'object') {
      target = {}
    }
    if (Array.isArray(source)) {
      return source.slice()
    }
    Object.keys(source).forEach(property => {
      const sourceProperty = source[property]
      if (typeof sourceProperty === 'object') {
        target[property] = this.objectMerge(target[property], sourceProperty)
      } else {
        target[property] = sourceProperty
      }
    })
    return target
  },

  /**
   * Extend object
   * @param {Object} target
   * @param {(Object|Array)} source
   * @param {String} prefix
   * @returns {Object}
   */
  objectExtend(target, source, prefix) {
    if (typeof target !== 'object') {
      target = {}
    }
    if (Array.isArray(source)) {
      target = source.slice()
      return target
    }
    if (prefix === undefined) {
      prefix = ''
    }
    Object.keys(source).forEach(property => {
      const targetProperty = target[prefix + property]
      if (targetProperty === null || targetProperty === undefined) {
        target[prefix + property] = {}
      }
      if (typeof property === 'object') {
        target[prefix + property] = this.objectUpdate(target[prefix + property], source[property])
      } else {
        target[prefix + property] = source[property]
      }
    })
    return target
  },

  /**
   * Update object
   * @param {Object} target
   * @param {(Object|Array)} source
   * @returns {Object}
   */
  objectUpdate(target, source) {
    if (typeof target !== 'object') {
      target = {}
    }
    if (Array.isArray(source)) {
      return source.slice()
    }
    Object.keys(target).forEach(property => {
      const sourceProperty = source[property]
      if (sourceProperty === null || sourceProperty === undefined) {
        target[property] = undefined
      } else if (typeof sourceProperty === 'object') {
        target[property] = this.objectUpdate(target[property], sourceProperty)
      } else {
        target[property] = sourceProperty
      }
    })
    return target
  },

  debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function() {
      // 据上一次触发时间间隔
      const last = +new Date() - timestamp

      // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
      if (last < wait && last > 0) {
        timeout = setTimeout(later, wait - last)
      } else {
        timeout = null
        // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
        if (!immediate) {
          result = func.apply(context, args)
          if (!timeout) context = args = null
        }
      }
    }

    return function(...args) {
      context = this
      timestamp = +new Date()
      const callNow = immediate && !timeout
      // 如果延时不存在，重新设定延时
      if (!timeout) timeout = setTimeout(later, wait)
      if (callNow) {
        result = func.apply(context, args)
        context = args = null
      }

      return result
    }
  }
}
